/**
 * OSAmI: Open Source Ambient Intelligence
 * Copyright (C) 2010 UJF.
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */
package org.osami.gateway.mediator.sensedata.internal;

import fr.liglab.adele.cilia.Data;
import org.osami.gateway.sensor.data.SenseData;

/**
 * Created by IntelliJ IDEA.
 * User: guillaume
 * Date: 12/08/11
 * Time: 15:19
 * To change this template use File | Settings | File Templates.
 */
public class SenseDataCsvTransformer {

    public static final String HEADER_V1 = "mbeancmd_values_v1";
    public static final String HEADER_COLUMN_NAMES = "time;domain;server;sname;mbean;value;";

    // Configuration properties not available in SenseData API

    /**
     * JMX domain name.
     */
    private String domain;

    /**
     * equivalent to J2EEServer name.
     */
    private String server;

    /**
     * Header shared by all messages.
     */
    private StringBuilder header;

    public void start() {
        header = new StringBuilder();
        header.append(HEADER_V1);
        header.append('\n');
        header.append(HEADER_COLUMN_NAMES);
        header.append('\n');
    }

    /**
     * Transform the given SenseData instance into a CSV message
     * accepted by JASMINe MbeanCmd dispatcher.
     * @param data input data containing the sense data
     * @return output data with a byte array
     */
    public Data process(Data data) {
        SenseData sd = (SenseData) data.getProperty(SenseData.DEFAULT_DATA_KEY);

        // Creates a new message, initialised with the common header
        StringBuilder message = new StringBuilder();
        message.append(header);

        // Append the line containing data (must respect the column order specified in header)
        writeLine(message,
                  String.valueOf(sd.getTimeStamp()), // time   -> timestamp
                  domain,                            // domain -> n/a
                  server,                            // server -> n/a
                  server,                            // sname  -> n/a
                  asObjectName(domain,
                               server,
                               sd),                  // mbean  -> JMX(SenseData)
                  String.valueOf(sd.getValue())      // value
                  );

        return new Data(message.toString().getBytes(), null, null);

    }

    private String asObjectName(String domain,
                                String server,
                                SenseData sd) {
        StringBuilder sb = new StringBuilder();
        sb.append(domain);
        sb.append(":");
        sb.append("J2EEServer=");
        sb.append(protect(server));
        sb.append(",");
        sb.append("SenseId=");
        sb.append(protect(sd.getSenseId()));
        sb.append(",");
        sb.append("SenseType=");
        sb.append(protect(sd.getType()));
        sb.append(",");
        sb.append("SenseLocation=");
        sb.append(protect(sd.getLocation()));
        sb.append(",");
        sb.append("SenseUnit=");
        sb.append(protect(sd.getUnit()));
        return sb.toString();
    }

    private String protect(String name) {
        // Ensure that no ':' leaks in the ObjectName
        return name.replace(':', '_')
                   .replace(' ', '_');
    }

    private static void writeLine(StringBuilder message, String... values) {

        boolean first = true;

        for (String value : values) {
            if (!first) {
                // Separates values with ';'
                message.append(";");
            } else {
                first = false;
            }

            message.append(value);
        }

        message.append('\n');
    }
}
